package com.parking.platform.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.parking.common.core.model.PageInfo;
import com.parking.common.core.model.StateData;
import com.parking.platform.dao.PlatformAccountLogsMapper;
import com.parking.platform.dao.PlatformAccountMapper;
import com.parking.platform.dao.PlatformAccountRoleMapper;
import com.parking.platform.dto.AccountDto;
import com.parking.platform.dto.PlatformAccountDto;
import com.parking.platform.dto.PlatformDto;
import com.parking.platform.dao.PlatformRoleMapper;
import com.parking.platform.entity.PlatformAccount;
import com.parking.platform.entity.PlatformAccountLogs;
import com.parking.platform.entity.PlatformAccountRole;
import com.parking.platform.entity.PlatformRole;
import com.parking.platform.exception.PlatformException;
import com.parking.platform.exception.PlatformExceptionCode;
import com.parking.platform.form.AddPlatformDataForm;
import com.parking.platform.form.PlatLoginForm;
import com.parking.platform.form.SelPlatformForm;
import com.parking.platform.form.UpPlatformPassForm;
import com.parking.platform.service.PlatformAccountService;
import javafx.application.Platform;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 香菜狗带
 * @since 2023年11月28日
 */
@Service
public class PlatformAccountServiceImpl extends ServiceImpl<PlatformAccountMapper, PlatformAccount> implements PlatformAccountService {
    @Autowired
    private PlatformAccountMapper platformAccountMapper;
    @Autowired
    private PlatformAccountRoleMapper platformAccountRoleMapper;
    @Autowired
    private PlatformRoleMapper platformRoleMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Resource
    private PlatformAccountLogsMapper platformAccountLogsMapper;




    /***
     * 登录方法
     * 参数：
     ("用户账号")：platformAccount;
     ("用户密码")：platformPass;
     ("请求头"):response
     */
    @Override
    public PlatformDto platLogin(PlatLoginForm form,String IpPath) {
        QueryWrapper<PlatformAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("platform_account",form.getPlatformAccount());
        wrapper.eq("platform_pass",form.getPlatformPass());
        //账号是否存在
        PlatformAccount platformAccount = platformAccountMapper.selectOne(wrapper);
        if(platformAccount==null){
            throw new PlatformException(PlatformExceptionCode.LOGIN_FAILED);
        }
        //账号状态是否正常
        if (platformAccount.getPlatformState()!= StateData.PLATFORM_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_NO);
        }
        PlatformDto dto = BeanUtil.toBean(platformAccount, PlatformDto.class);
        PlatformRole platformRole = platformRoleMapper.selectById(platformAccount.getPlatformRoleId());
        //角色状态是否正常
        if (platformRole.getPlatformRoleState()!= StateData.PLATFORM_ROLE_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ROLE_STATE);
        }
//        //判断是否登录
//        QueryWrapper<PlatformAccountLogs> logWrapper = new QueryWrapper<>();
//        logWrapper.eq("platform_account_id",platformAccount.getPlatformId());
//        logWrapper.eq("platform_login_state",StateData.PLATFORM_LOGS_ISNOT_LOGIN);
//        PlatformAccountLogs platformAccountLogs = platformAccountLogsMapper.selectOne(logWrapper);
//        if (ObjectUtil.isNotEmpty(platformAccountLogs)) {
//                throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_LOGGED_IN);
//        }
        dto.setPlatformRoleId(platformRole.getPlatformRoleId());
        dto.setPlatformRoleName(platformRole.getPlatformRoleName());
        dto.setPlatformPower(platformRole.getPlatformPower());
        //消息队列
        PlatformAccountLogs logs = new PlatformAccountLogs();
        logs.setPlatformLoginAccount(dto.getPlatformAccount());
        logs.setPlatformLoginTime(LocalDateTime.now());
        logs.setPlatformAccountId(dto.getPlatformId());
        logs.setPlatformLoginAdress(IpPath);
        //创建map集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccountLogs",logs);
        //使用消息队列
        rabbitTemplate.convertAndSend("platLogin",map);
        return dto;
    }
    /***
     * 根据Id查询平台账号
     * 参数：
     * 令牌:authorization
     */
    @Override
    public PlatformDto findPlatformById(Integer platformId) {
        PlatformAccount account = platformAccountMapper.selectById(platformId);
        //账号是否存在
        if (account==null) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_NO);
        }
        //账号状态是否正常
        if (account.getPlatformState()!= StateData.PLATFORM_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_NO);
        }
        PlatformDto dto = BeanUtil.toBean(account, PlatformDto.class);
        PlatformRole platformRole = platformRoleMapper.selectById(account.getPlatformRoleId());
        dto.setPlatformRoleName(platformRole.getPlatformRoleName());
        return dto;
    }
    /**
     * 最高管理员
     * 启用平台账号状态
     * 参数
     * 令牌：authorization=>adminId
     * 账号状态：state
     * 账号Id：platformId
     * */
    @Override
    @Transactional
    public void enablePlatStateById(Integer platformId, Integer adminId) {
        PlatformAccount account = platformAccountMapper.selectById(platformId);
        if (adminId==platformId) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_MY);
        }
        //账号是否存在
        if (account==null) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_NO);
        }
        //账号状态是否被删除
        if (account.getPlatformState()== StateData.PLATFORM_STATE_DELETE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_DELETE);
        }
        if (account.getPlatformState()== StateData.PLATFORM_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_ENABLE);
        }
        PlatformRole platformRole = platformRoleMapper.selectById(account.getPlatformRoleId());
        if (platformRole.getPlatformRoleState()!= StateData.PLATFORM_ROLE_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ROLE_STATE);
        }
        account.setPlatformState(StateData.USER_STATE_ENABLE);
        platformAccountMapper.updateById(account);
        //消息队列修改日志信息
        //消息队列修改日志信息
        account.setPlatformUpdatePerson(adminId.toString());
        account.setPlatformUpdateTime(LocalDateTime.now());
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccount",account);
        rabbitTemplate.convertAndSend("upPlatformData",map);
    }
    /**
     * 禁用平台账号状态
     * 参数
     * 令牌：authorization=>adminId
     * 账号状态：state
     * 账号Id：platformId
     * */
    @Transactional
    @Override
    public void downPlatStateById(Integer platformId, Integer adminId) {
        if (adminId==platformId) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_MY);
        }
        PlatformAccount account = platformAccountMapper.selectById(platformId);
        if (adminId==platformId) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_MY);
        }
        //账号是否存在
        if (account==null) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_NO);
        }
        //账号状态是否被删除
        if (account.getPlatformState()== StateData.PLATFORM_STATE_DELETE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_DELETE);
        }
        if (account.getPlatformState()== StateData.PLATFORM_STATE_DISABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_DOWN);
        }
        account.setPlatformState(StateData.PLATFORM_STATE_DISABLE);
        platformAccountMapper.updateById(account);
        //消息队列修改日志信息
        account.setPlatformUpdatePerson(adminId.toString());
        account.setPlatformUpdateTime(LocalDateTime.now());
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccount",account);
        rabbitTemplate.convertAndSend("upPlatformData",map);
    }
    /**
     * 删除平台账号
     * 参数
     * 令牌：authorization=>adminId
     * 账号状态：state
     * 账号Id：platformId
     * */
    @Transactional
    @Override
    public void deletePlatStateById(Integer platformId, Integer adminId) {
        if (adminId==platformId) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_MY);
        }
        PlatformAccount account = platformAccountMapper.selectById(platformId);
        if (adminId==platformId) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_MY);
        }
        //账号是否存在
        if (account==null) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_NO);
        }
        //账号状态是否被删除
        if (account.getPlatformState()== StateData.PLATFORM_STATE_DELETE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_DELETE);
        }
        account.setPlatformState(StateData.PLATFORM_STATE_DELETE);
        platformAccountMapper.updateById(account);
        //消息队列修改日志信息
        account.setPlatformUpdatePerson(adminId.toString());
        account.setPlatformUpdateTime(LocalDateTime.now());
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccount",account);
        rabbitTemplate.convertAndSend("upPlatformData",map);
    }
    /***
     * 最高管理员
     * 添加平台账号
     * 参数：
     * 令牌：authorization=>adminId
     * ("平台账号")：platformAccount;
     * ("平台密码")：platformPass;
     */
    @Transactional
    @Override
    public void addPlatformData(AddPlatformDataForm form, Integer adminId) {
        QueryWrapper<PlatformAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("platform_account",form.getPlatformAccount());
        PlatformAccount account = platformAccountMapper.selectOne(wrapper);
        if(account!=null){
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_EXIST);
        }
        PlatformAccount platformAccount = BeanUtil.toBean(form, PlatformAccount.class);
        platformAccount.setPlatformState(StateData.PLATFORM_STATE_ENABLE);
        platformAccountMapper.insert(platformAccount);
        QueryWrapper<PlatformAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("platform_account",form.getPlatformAccount());
        queryWrapper.eq("platform_pass",form.getPlatformPass());
        PlatformAccount selectOne = platformAccountMapper.selectOne(queryWrapper);
        PlatformAccountRole accountRole = new PlatformAccountRole();
        accountRole.setPlatformRoleId(form.getPlatformRoleId());
        platformAccountRoleMapper.insert(accountRole);
        //消息队列修改日志信息
        platformAccount.setPlatformTime(LocalDateTime.now());
        platformAccount.setPlatformAddPerson(String.valueOf(adminId));
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccount",platformAccount);
        rabbitTemplate.convertAndSend("addPlatformData",map);
    }
    /**
     * 查询全部平台账号
     * 参数：
     * 账号：platformAccount
     * 角色名：platformRoleName
     * 返回值：
     *  List<PlatformDto>
     *
     */
    @Override
    public PageInfo findPlatformAll(SelPlatformForm form) {
        Page<PlatformAccount> page = new Page<>(form.getPageNum()!=null?form.getPageNum():1, form.getPageSize()!=null?form.getPageSize():6);
        QueryWrapper<PlatformAccount> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(form.getPlatformAccount())) {
            wrapper.eq("platform_account",form.getPlatformAccount());
        }
        if(form.getState()!=-1){
            wrapper.eq("platform_state",form.getState());
        }
        platformAccountMapper.selectPage(page,wrapper);
        List<AccountDto> list = BeanUtil.copyToList(page.getRecords(), AccountDto.class);
        for (AccountDto accountDto : list) {
            QueryWrapper<PlatformAccountRole> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("platform_account_id",accountDto.getPlatformId());
            PlatformAccountRole accountRole = platformAccountRoleMapper.selectOne(roleQueryWrapper);
            PlatformRole platformRole = platformRoleMapper.selectById(accountRole.getPlatformRoleId());
            accountDto.setPlatformRoleName(platformRole.getPlatformRoleName());
            accountDto.setPlatformRoleId(platformRole.getPlatformRoleId());
            if (ObjectUtil.isNotEmpty(accountDto.getPlatformAddPerson())) {
                accountDto.setPlatformAddPersonName(platformAccountMapper.selectById(accountDto.getPlatformAddPerson()).getPlatformAccount());
            }
            if (ObjectUtil.isNotEmpty(accountDto.getPlatformUpdatePerson())) {
                accountDto.setPlatformUpdatePersonName(platformAccountMapper.selectById(accountDto.getPlatformUpdatePerson()).getPlatformAccount());
            }
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(list);
        return pageInfo;
    }
    /***
     * 最高管理员
     * 修改平台账号
     * 参数：
     * 令牌：authorization=>adminId
     * 令牌：authorization
     */
    @Transactional
    @Override
    public void upPlatformData(Integer platformId, String platformAccount, Integer adminId) {
        PlatformAccount account = platformAccountMapper.selectById(platformId);
        //账号是否存在
        if (account==null) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_NO);
        }
        //账号状态是否被删除
        if (account.getPlatformState()== StateData.PLATFORM_STATE_DELETE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_DELETE);
        }
        account.setPlatformAccount(platformAccount);
        System.out.println("=============="+account);
        platformAccountMapper.updateById(account);
        //消息队列修改日志信息
        account.setPlatformUpdatePerson(adminId.toString());
        account.setPlatformUpdateTime(LocalDateTime.now());
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccount",account);
        rabbitTemplate.convertAndSend("upPlatformData",map);
    }
    /***
     * 退出登录方法
     * 参数：
     * ("平台Id")：platformId;
     */
    @Override
    public void PlatformLogOff(Integer platformId) {
        QueryWrapper<PlatformAccountLogs> wrapper = new QueryWrapper<>();
        wrapper.eq("platform_account_id",platformId);
        wrapper.eq("platform_login_state",StateData.PLATFORM_LOGS_ISNOT_LOGIN);
        List<PlatformAccountLogs> platformAccountLogs = platformAccountLogsMapper.selectList(wrapper);
        for (PlatformAccountLogs platformAccountLog : platformAccountLogs) {
            if (platformAccountLog==null) {
                throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_NO_LOGIN);
            }
            platformAccountLog.setPlatformLoginState(StateData.PLATFORM_LOGS_LOGIN);
            platformAccountLogsMapper.updateById(platformAccountLog);
        }

    }

    @Override
    public PlatformAccount getPlatformById(Integer platformId) {
        PlatformAccount platformAccount = platformAccountMapper.selectById(platformId);
        return platformAccount;
    }

    @Override
    public void UpPlatformPass(UpPlatformPassForm form, Integer platformId) {
        PlatformAccount account = platformAccountMapper.selectById(platformId);
        //账号是否存在
        if (account==null) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_IS_NO);
        }
        //账号状态
        if (account.getPlatformState()!= StateData.USER_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ACCOUNT_STATE_NO);
        }
        PlatformRole platformRole = platformRoleMapper.selectById(account.getPlatformRoleId());
        if (platformRole.getPlatformRoleState()!= StateData.PLATFORM_ROLE_STATE_ENABLE) {
            throw new PlatformException(PlatformExceptionCode.FAILED_ROLE_STATE);
        }
        System.out.println(form.getOldPass());
        System.out.println(account.getPlatformPass());
        System.out.println(form.getOldPass()==account.getPlatformPass());
        if (!form.getOldPass().equals(account.getPlatformPass())) {
            throw new PlatformException(PlatformExceptionCode.LOGIN_PLATFORM_PAS_NO);
        }
        account.setPlatformPass(form.getNewPass());
        platformAccountMapper.updateById(account);
        //消息队列修改日志信息
        account.setPlatformUpdatePerson(platformId.toString());
        account.setPlatformUpdateTime(LocalDateTime.now());
        HashMap<String, Object> map = new HashMap<>();
        map.put("platformAccount",account);
        rabbitTemplate.convertAndSend("upPlatformData",map);


    }
}
